package com.example.backed.service.impl;

import com.example.backed.entity.User;
import com.example.backed.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 尝试将username解析为用户ID
        try {
            Long userId = Long.parseLong(username);
            User user = loadUserById(userId);
            if (user != null) {
                return user;
            }
        } catch (NumberFormatException ignored) {
            // 不是用户ID，继续尝试按用户名查询
        }
        
        // 从数据库中按用户名查询用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在：" + username);
        }
        return user;
    }
    
    /**
     * 通过用户ID加载用户
     *
     * @param userId 用户ID
     * @return 用户信息
     */
    public User loadUserById(Long userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在（ID）：" + userId);
        }
        return user;
    }
} 